var ccsp = new PDDCsp();
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    switch (message.greeting) {
        case 'skuReady':
            ccsp.skuReady(message, sender, sendResponse);
            break;
        case 'orderSended':
            ccsp.orderSended(message, sender, sendResponse);
            break;
        case "sendInfo":
            ccsp.sendInfo(message, sender, sendResponse);
            break;
        case 'orderProcess':
        	ccsp.orderProcess(message, sender, sendResponse);
            break;
        case 'updateAddr':
            ccsp.updateAddr(message, sender, sendResponse);
            break;
        case 'injectJS':
            ccsp.injectJS(message, sender, sendResponse);
            break;
        case 'detailRefresh':
            ccsp.detailRefresh(message, sender, sendResponse);
            break;
        case 'accountRefresh':
            ccsp.accountRefresh(message, sender, sendResponse);
            break;
        case 'getAnti':
            ccsp.getAnti(message, sender, sendResponse);
            break;
        case 'startAutoPay':
            ccsp.startAutoPay(message, sender, sendResponse);
            break;
        case 'ces':
            alert('ces');
            break;
        case 'autoSendTime':
            ccsp.autoSendTime(message);
            break;
        case 'getSkuByDOM':
            ccsp.getSkuByDOM(message, sender, sendResponse)
            .then((result) => {
                sendResponse(result);
            })
            .catch((error) => {
                sendResponse({
                    success: false,
                    error: error.message,
                    message: '处理过程中出错'
                });
            });
            break;
        default:
            break;
    }
    return true;
});

if (window.location.href.indexOf("https://mobile.yangkeduo.com/personal.html") != -1) {
    const nickname = document.querySelector("p.nickname").innerHTML;
    // alert(nickname);
    chrome.runtime.sendMessage({greeting: 'nowAccount', data: nickname});
}

if (window.location.href.indexOf("https://mobile.yangkeduo.com/goods.html") != -1 || window.location.href.indexOf("https://mobile.yangkeduo.com/goods2.html") != -1 || window.location.href.indexOf("https://mobile.yangkeduo.com/goods1.html") != -1) {
    // 加一个按钮
    // alert(1);
    // const sku_button = document.createElement("button");

    // sku_button.textContent = '手动采集';
    // // sku_button.style.position = "";
    // sku_button.style.position = 'fixed';
    // sku_button.style.right = '10px';
    // sku_button.style.width = '100px';
    // sku_button.style.height = '50px';
    // sku_button.style.bottom = '20px';
    // sku_button.style.background = 'blue';
    // sku_button.style.color = 'white';
    // sku_button.addEventListener('click', () => {
        
    // });

    // document.body.appendChild(sku_button);
}

// alert(window.location.href);
if (window.location.href.indexOf("https://mclient.alipay.com/h5pay/landing/index.html") != -1) {
    chrome.runtime.sendMessage({greeting: 'autoPay'});
}

// if (window.location.href.indexOf("https://mobile.yangkeduo.com/search_result.html") != -1 || false) {
//     (function() {
//       const originalXHR = window.XMLHttpRequest;

//       window.XMLHttpRequest = function() {
//         const xhr = new originalXHR();

//         // 重写onreadystatechange以捕获响应
//         const originalOnReadyStateChange = xhr.onreadystatechange;
//         xhr.onreadystatechange = function() {
//           if (xhr.readyState === 4) { // 请求完成
//             if (xhr.status === 200) {
//               console.log('捕获到XHR响应:', xhr.responseText);
//               // chrome.runtime.sendMessage({
//               //   type: 'xhr_data',
//               //   url: xhr.responseURL,
//               //   data: xhr.responseText
//               // });
//             }
//           }
//           if (originalOnReadyStateChange) {
//             originalOnReadyStateChange.apply(xhr, arguments);
//           }
//         };

//         return xhr;
//       };
//     })();
//     const html = `
//         <div style="position: fixed; z-index: 100000; width: 400px; height: 600px; background-color: #53a7ff; border-radius: 10px; bottom: 0; right: 20px; text-align: center; padding: 15px;">
//             <div style="color: white;">操作窗口</div>
//             <div style="background-color: white; width: 100%; height: 500px; overflow: scroll;">
//                 <ul id="result">

//                 </ul>
//             </div>
//             <button id="getParse" style="border-radius: 5px;font-size: 12px; padding: 5px 11px;">开始</button>
//         </div>
//     `.split('\n')
//     .map(line => line.trim())
//     .join('');
//     document.body.insertAdjacentHTML('afterbegin', html);
//     var div = document.getElementById('getParse');
//     div.addEventListener('click', (e) => {
//         let html = document.documentElement.children[1].children[3].innerHTML;
//         chrome.runtime.sendMessage({greeting: 'searchResult', html: html});
//     });
// }

// 点击事件
const parentElement = document.body;

parentElement.addEventListener('click', (event) => {

    // 重置页面缓存
    const isTargetClear = event.target.id === 'autoorderClear';
    if (isTargetClear) {
        chrome.runtime.sendMessage({greeting: 'autoorderClear'});
    }

    // console.log(event.target);
    const isTargetDOM = event.target.id === 'getSkuDOMBtn';
    const isTargetDOMText = event.target.id === 'getSkuDOMText'
    if (isTargetDOM || isTargetDOMText) {
        // 获取链接
        console.log('DOM content');
        // var url = document.getElementsByClassName('origin-urls')[0].querySelector('.el-input__inner').value
        var urls = document.getElementsByClassName('origin-urls');
        if (urls.length == 0) {
            return;
        }

        // 带上三个参数 url erp的tabid 视频号平台商品id
        const platform_product_id = document.getElementById('platform-product-id').innerText;
        for (var i = 0; i < urls.length; i++) {
            var is_refresh = 0;
            if (i == urls.length - 1) {
                is_refresh = 1;
            }
            const url = urls[i].querySelector('.el-input__inner').value;
            if (url == '') {
                return;
            }
            if (urls.length == 1) {
                // 如果只有一个url  直接发送
                chrome.runtime.sendMessage({
                    greeting: "getSkuByDOM", 
                    platform_product_id: platform_product_id, 
                    url: url, 
                    is_refresh: is_refresh
                }, (response) => {
                    console.log(response)
                });
                break;
            }

            if (is_refresh == 1) {
                // 延后一点时间发送
                const timeoutId = setTimeout(() => {
                    chrome.runtime.sendMessage({
                        greeting: "getSkuByDOM", 
                        platform_product_id: platform_product_id, 
                        url: url, 
                        is_refresh: is_refresh
                    }, (response) => {
                        console.log(response)
                    });
                }, 2500);
            } else {
                // 立即发送
                chrome.runtime.sendMessage({
                    greeting: "getSkuByDOM", 
                    platform_product_id: platform_product_id, 
                    url: url, 
                    is_refresh: is_refresh
                }, (response) => {
                    console.log(response)
                });
            }
            
        }
    }



    const isTarget = event.target.id === 'getSkuBtn';
    const isTargetText = event.target.id === 'getSkuText'
    if (isTarget || isTargetText) {
        // 获取链接
        // var url = document.getElementsByClassName('origin-urls')[0].querySelector('.el-input__inner').value
        var urls = document.getElementsByClassName('origin-urls');
        if (urls.length == 0) {
            return;
        }

        // 带上三个参数 url erp的tabid 视频号平台商品id
        const platform_product_id = document.getElementById('platform-product-id').innerText;
        for (var i = 0; i < urls.length; i++) {
            var is_refresh = 0;
            if (i == urls.length - 1) {
                is_refresh = 1;
            }
            const url = urls[i].querySelector('.el-input__inner').value;
            if (url == '') {
                return;
            }
            if (urls.length == 1) {
                // 如果只有一个url  直接发送
                chrome.runtime.sendMessage({
                    greeting: "getSku", 
                    platform_product_id: platform_product_id, 
                    url: url, 
                    is_refresh: is_refresh
                }, (response) => {
                    console.log(response)
                });
                break;
            }

            if (is_refresh == 1) {
                // 延后一点时间发送
                const timeoutId = setTimeout(() => {
                    chrome.runtime.sendMessage({
                        greeting: "getSku", 
                        platform_product_id: platform_product_id, 
                        url: url, 
                        is_refresh: is_refresh
                    }, (response) => {
                        console.log(response)
                    });
                }, 2500);
            } else {
                // 立即发送
                chrome.runtime.sendMessage({
                    greeting: "getSku", 
                    platform_product_id: platform_product_id, 
                    url: url, 
                    is_refresh: is_refresh
                }, (response) => {
                    console.log(response)
                });
            }
            
        }
    }

    const isAutoSendOrder = event.target.id === 'autoSendOrder';
    const isAutoSendOrderText = event.target.id === 'autoSendOrderText';
    if (isAutoSendOrder || isAutoSendOrderText) {
        // 自动发货
        chrome.runtime.sendMessage({greeting: 'autoSendOrder', start: 1, autoType: 'auto'});
    }
    // 自动下单
    const isAutoOrder = event.target.id === 'autoOrder';
    const isAutoOrderText = event.target.id === 'autoOrderText';
    if (isAutoOrder || isAutoOrderText) {
        // 保存数据（异步操作）
        chrome.runtime.sendMessage({greeting: 'autoOrder', autoType: 'auto', start: 1});
    }

    // 关闭自动下单
    const isautoorderClose = event.target.id === 'autoorderClose';
    const isautoorderCloseText = event.target.id === 'autoorderCloseText';

    if (isautoorderClose || isautoorderCloseText) {
        chrome.runtime.sendMessage({greeting: 'closeAuto'});
    }

    const isautoorderStop = event.target.id === 'autoorderStop';
    if (isautoorderStop) {
        chrome.runtime.sendMessage({greeting: 'closeAuto'});
    }

    const isautoorderRestart = event.target.id === 'autoorderRestart';
    if (isautoorderRestart) {
        chrome.runtime.sendMessage({greeting: 'startAuto'});
    }

    //关闭自动同步
    const isautosendClose = event.target.id === 'autosendClose';
    const isautosendCloseText = event.target.id === 'autosendCloseText';
    if (isautosendClose || isautosendCloseText) {
        chrome.runtime.sendMessage({greeting: 'closeAutoSend'});
    }

    const isautosendStop = event.target.id === 'autosendStop';
    if (isautosendStop) {
        //暂停
        chrome.runtime.sendMessage({greeting: 'stopAutoSend'});
    }

    const isautosendRestart = event.target.id === 'autosendRestart';
    if (isautosendRestart) {
        //开启
        chrome.runtime.sendMessage({greeting: 'startAutoSend'});
    }

    // 手动下单
    var isTargetOrderBtn = false;
    console.log(event.target.className);
    if (event.target && event.target.className && event.target.className.indexOf('targetOrderBtn') != -1) {
        isTargetOrderBtn = true;
    }
    const isTargetOrderText = event.target.className === 'targetOrderText';
    
    var btn_text = false;
    if (isTargetOrderText) {
		// var order_data = JSON.parse(event.target.parentElement.children[1].innerHTML)
        btn_text = event.target.parentElement;
    }

    if (isTargetOrderBtn) {
    	//var order_data = JSON.parse(event.target.children[0].children[1].innerHTML);
        btn_text = event.target.children[0];
    }

    if (btn_text) {
        const platform_order_id = btn_text.querySelector("span.target_data_platform_order_id").innerHTML;
        const platform_sku_id = btn_text.querySelector("span.target_data_platform_sku_id").innerHTML;
        const link_skuID = btn_text.querySelector("span.target_data_linksku_id").innerHTML;
        const real_user_name = btn_text.querySelector("span.target_data_real_user_name").innerHTML;
        const order_data = {
            platform_order_id: platform_order_id,
            platform_sku_id: platform_sku_id,
            link_skuID: link_skuID,
            real_user_name: real_user_name
        };
        chrome.runtime.sendMessage({greeting: 'handOrder', order_data: order_data, autoType: 'hand'});
    } 

    // 同步采购订单
    var isTargetOrderSnAsyncBtn = false;

    if (event.target.className && event.target.className.indexOf("orderSnAsyncBtn") != -1) {
        isTargetOrderSnAsyncBtn = true;
    }

    const isTargetOrderSnAsyncText = event.target.className === 'orderSnAsyncText';

    if (isTargetOrderSnAsyncBtn || isTargetOrderSnAsyncText) {

        var is_log_span = event.target.querySelector('.is_log');
        console.log(is_log_span);
        var is_log = 0;

        var async_text = event.target.textContent;
        async_text = async_text.trim();
        const async_arr = async_text.split(' ');
        console.log(async_arr);
        if (async_arr.length < 2) {
            return;
        }

        if (is_log_span && is_log_span.textContent.trim() == 1) {
            is_log = 1;
        }

        chrome.runtime.sendMessage({greeting: 'orderSnAsync', orderSn: async_arr[1], is_log: is_log});
    }

    //查看 订单号
    const isTargetOrderSn = event.target.className === 'purchase_order_sn';
    var isTargetOrderSnSpan = false;

    if (event.target.className && event.target.className.indexOf('purchase_order_sn') != -1) {
        isTargetOrderSnSpan = true;
    }

    if (isTargetOrderSn || isTargetOrderSnSpan) {
        const order_sn = event.target.textContent;
        chrome.runtime.sendMessage({greeting: 'showPurchaseOrder', order_sn: order_sn, type: 'hand'});
    }
    // 也是查订单号 ellink方式
    if (event.target.className && event.target.className.indexOf('pur_order_sn') != -1) {
        var order_sn = event.target.querySelector('.order_sn').textContent;
        if (order_sn) {
            chrome.runtime.sendMessage({greeting: 'showPurchaseOrder', order_sn: order_sn, type: 'hand'});
        }
    }
    // alert(event.target.className);
    // 加账号
    const isTargetAccount = event.target.id === 'addAccount';
    const isTargetAccountText = event.target.id === 'addAccountText';
    if (isTargetAccount || isTargetAccountText) {
        chrome.runtime.sendMessage({greeting: 'addAccount'});
    }
    // 切换账号
    var isTargetSetAccountBtn = false;
    if (event.target.className && event.target.className.indexOf("setAccount") != -1) {
        isTargetSetAccountBtn = true;
    }


    const isTargetSetAccountText = event.target.className === 'setAccountText';
    if (isTargetSetAccountBtn || isTargetSetAccountText) {
        const setText = event.target.textContent.trim();
        const setArr = setText.split(' ');
        chrome.runtime.sendMessage({greeting: 'setAccount', acct_id: setArr[1]});
    }

    // 支付账号
    const isTargetPayAccount = event.target.id === 'savePayAccount';
    if (isTargetPayAccount) {
        // 找到支付密码
        const pwd = document.querySelector('#paypwd').value;
        const name = document.querySelector('#payname').value;
        chrome.runtime.sendMessage({greeting: 'savePay', pwd: pwd, name: name});
    }

    //查看发货物流
    if (event.target.className && event.target.className.indexOf('check-ship') != -1) {

        const check_order_sn = event.target.querySelector('.check-ship-orderSn').textContent;
        chrome.runtime.sendMessage({greeting: 'checkShip', order_sn: check_order_sn});
    }
    //查看退货物流
    if (event.target.className && event.target.className.indexOf('refund_ship') != -1) {
        const aftersale_id = event.target.querySelector('.aftersale_id').textContent;
        const aftersale_ship_order_sn = event.target.querySelector('.aftersale_order_sn').textContent;
        chrome.runtime.sendMessage({greeting: 'refundShip', aftersale_id: aftersale_id, order_sn: aftersale_ship_order_sn});
    }

    const isTargetAftersale = event.target.className === 'aftersale';
    var isTargetAftersaleBtn = false;
    // console.log(event.target);
    if (event.target.className && event.target.className.indexOf('aftersale_send') != -1) {
        isTargetAftersaleBtn = true;
    }

    if (isTargetAftersale || isTargetAftersaleBtn) {

        const aftersale_order_sn = event.target.querySelector('.aftersale_order_sn').textContent;
        const aftersale_type = event.target.querySelector('.aftersale_type').textContent;
        const after_sale_order_id = event.target.querySelector('.after_sale_order_id').textContent;
        chrome.runtime.sendMessage({greeting: 'afterSaleHand', order_sn: aftersale_order_sn, type: aftersale_type, after_sale_order_id: after_sale_order_id});
    }

    const isTargetAftersaleDetail = event.target.className === 'aftersale_detail';
    var isTargetAftersaleDetailBtn = false;

    if (event.target.className && event.target.className.indexOf('aftersale_detail') != -1) {
        isTargetAftersaleDetailBtn = true;
    }

    if (isTargetAftersaleDetail || isTargetAftersaleDetailBtn) {
        const aftersale_id = event.target.querySelector('.aftersale_id').textContent;
        const aftersale_detail_order_sn = event.target.querySelector('.aftersale_order_sn').textContent;
        chrome.runtime.sendMessage({greeting: 'afterSaleDetail', aftersale_id: aftersale_id, order_sn: aftersale_detail_order_sn});
    }

    const isTargetAutoAftersale = event.target.id === 'start_auto_aftersale';
    if (isTargetAutoAftersale) {
        chrome.runtime.sendMessage({greeting: 'autoAfter'});
    }

    const isTargetAutoAftersaleClose = event.target.id === 'auto-after-close';
    if (isTargetAutoAftersaleClose) {
        chrome.runtime.sendMessage({greeting: 'autoAfterClose'});
    }

    const isParseGoods = event.target.id === 'goods-parse';
    if (isParseGoods) {
        chrome.runtime.sendMessage({greeting: 'goodsParse'});
    }

    if (event.target.className && event.target.className.indexOf('order_mall') != -1) {
        // 获取sn
        const order_mall_order_sn = event.target.querySelector('.order_sn').textContent;
        chrome.runtime.sendMessage({greeting: 'orderMall', order_sn: order_mall_order_sn});   
    }
});

